<?php

namespace app\admin\model;

use think\Model;

use think\Db;
use think\Request;

class Sale extends Model
{
    public function getsalepay($res)
    {
        $page = $res['page'];
        $limit = $res['pageSize'];
        //搜索条件
        $salewhere = $this->statuswhere($res['status'])['salewhere'];
        //搜索（公司名和订单号） b关系表 c 销售表
        if (isset($res['dname']) && $res['dname']) {
            //公司名查询
            $companyname = array_column(model('company')->getcompanyname($res), 'id');
            if ($companyname) {
                $maps['c.co_id'] = array('in', $companyname);
                $maps['c.co_branch_id'] = array('in', $companyname);
            }
            $maps['b.sale_id'] = array('like', '%' . removeBlank($res['dname']) . '%');//订单号
        } else {
            $maps = array();
        }
        if ($res['status'] == 7) {
            //支票收到
            $join = [
                ['sale_pay_index b', 'a.id=b.sale_payreg_id', 'LEFT'],//关联表
                ['sale c', 'c.id=b.sale_id', 'LEFT'],//销售表
                ['sale_pay_cheque d', 'a.id=d.sale_payreg_id', 'LEFT'],//支票表
            ];
        } else if ($res['status'] == 1) {
            //新订单
            $join = [
                ['sale_pay_index b', 'a.id=b.sale_payreg_id', 'LEFT'],//关联表
                ['sale c', 'c.id=b.sale_id', 'LEFT'],//销售表
                ['sale_make d', 'c.id=d.sale_id', 'LEFT'],//配货表
            ];
        } else {
            // 待收款 确认收款 已完成 逾期 坏账
            $join = [
                ['sale_pay_index b', 'a.id=b.sale_payreg_id', 'LEFT'],//关联表
                ['sale c', 'c.id=b.sale_id', 'LEFT'],//销售表
            ];
        }
        if ($res['status'] == 4) {
            // (已完成包括成功，或者失败)
            if (isset($res['code']) && $res['code']) {
                //标签的切换设置
                if ($res['code'] != 11) {
                    $salewhere['a.paytype_id'] = $res['code'];
                    $salewhereor['a.paytype_id'] = $res['code'];
                }
            }
            //7天内失败的订单
            $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
            //7天之前
            $sevenday = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y')) - 1;
            $salewhereor['a.fail_at'] = ['between', "$sevenday,$endToday"];
            $salewhereor['a.check_id'] = session('userid');
            //时间搜索
            if (isset($res['monthday']) && $res['monthday']) {
                $yearmonth = getTimeDate(null, 10);
                $two = explode('-', $res['monthday']);
                if (strlen($two[1]) == 1) {
                    $monthday = $two[0] . '-' . '0' . $two[1];
                } else {
                    $monthday = $res['monthday'];
                }
                //如果是当前月的话，就查询7天的数据
                if ($yearmonth != $monthday) {
                    //这个月开始的日期
                    $one = strtotime($monthday . '-01');
                    //查询这个月的完成的数据
                    $two = strtotime(date('Y-m-d', strtotime("$monthday +1 month -1 day"))) + 86399;
                    $salewhere['a.success_at'] = ['between', "$one,$two"];
                    $salewhereor['a.fail_at'] = ['between', "$one,$two"];
                }
            }
            //数据
            $saledata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->whereOr(function ($query) use ($salewhereor) {
                $query->where($salewhereor);
            })->field('a.*,b.sale_id,c.id as saleid,c.priority,c.pay,c.pledge,c.saler_id,c.co_id,c.co_branch_id,c.create_at as start_at,c.finish_at')->page($page, $limit)->select();

            //总数
            $countdata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->whereOr(function ($query) use ($salewhereor) {
                $query->where($salewhereor);
            })->field('a.id,a.paytype_id')->select();

        } else {
            if ($res['status'] == 7) {
                $field = 'a.*,b.sale_id,c.priority,c.id as saleid,c.pay,c.pledge,c.saler_id,c.co_id,c.co_branch_id,c.create_at as start_at,c.finish_at,d.id as chequeid,d.got_id,d.got_at,d.update_id as upidname,d.update_at as updates';
            } else {
                $field = 'a.*,b.sale_id,c.priority,c.id as saleid,c.pay,c.pledge,c.saler_id,c.co_id,c.co_branch_id,c.create_at as start_at,c.finish_at';
            }
            //支票收到 新订单 待收款 确认收款 逾期 坏账 （数据）
            $saledata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->field($field)->page($page, $limit)->select();
            //总数
            $countdata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($salewhere) {
                $query->where($salewhere);
            })->where(function ($query) use ($maps) {
                $query->whereOr($maps);
            })->field('a.id,a.paytype_id')->select();
        }
        //对数据进行处理
        foreach ($saledata as $saledatakey => $saledataval) {
            //设置间隔时间
            $timedate = gettime($saledataval['start_at'], time());
            $saledata[$saledatakey]['interval_time'] = $timedate['hour'] . ":" . $timedate['min'] . ':' . $timedate['sec'];

            //业务员
            $saledata[$saledatakey]['saler_name'] = getinfo($saledataval['saler_id'], 'admin')['nickname'];

            //公司名称
            $saledata[$saledatakey]['company_name'] = getinfo($saledataval['co_id'], 'company')['name'];

            //分公司名称
            $saledata[$saledatakey]['company_branch_name'] = getinfo($saledataval['co_branch_id'], 'co_branch')['name'];

            //付款方式
            $pay_typewhere['mkey'] = 'sale_pay_type_' . $saledataval['paytype_id'];
            $saledata[$saledatakey]['paytype_name'] = getlangname('multi_lang', $pay_typewhere, $res['lang']);

            //收款日期
            $saledata[$saledatakey]['pay_date'] = getTimeDate($saledataval['pay_day'], 15);
            //已经完成 坏账(才有会计)
            if ($res['status'] == 4 || $res['status'] == 6) {
                //会计名称
                $saledata[$saledatakey]['check_name'] = getinfo($saledataval['check_id'], 'admin')['nickname'];
                $saledata[$saledatakey]['time'] = time();
                if ($saledataval['success_at'] > 0) {
                    //支付成功时间
                    $saledata[$saledatakey]['succes_fail_date'] = getTimeDate($saledataval['success_at'], 12);
                    $saledata[$saledatakey]['class'] = 'green';//成功绿色
                } else {
                    //支付失败
                    $saledata[$saledatakey]['succes_fail_date'] = getTimeDate($saledataval['fail_at'], 12);
                    $saledata[$saledatakey]['class'] = 'red';//失败红色
                }
            } else {
                //没有支付过的
                $saledata[$saledatakey]['class'] = '';
            }

            //编辑时间和编辑人
            $saledata[$saledatakey]['managename'] = getinfo($saledataval['update_id'], 'admin')['nickname'];
            $saledata[$saledatakey]['update_date'] = getTimeDate($saledataval['update_at'], 12);

            //签收人和签收时间
            if (isset($saledataval['got_id']) && $saledataval['got_id'] > 0) {
                //表示有签收人
                $saledata[$saledatakey]['got_name'] = getinfo($saledataval['got_id'], 'admin')['nickname'];
                $saledata[$saledatakey]['got_date'] = getTimeDate($saledataval['got_at'], 12);
            }
            //支票收到中的编辑编辑时间
            if (isset($saledataval['upidname']) && $saledataval['updates'] > 0) {
                //表示有签收人
                $saledata[$saledatakey]['upname'] = getinfo($saledataval['upidname'], 'admin')['nickname'];
                $saledata[$saledatakey]['update'] = getTimeDate($saledataval['updates'], 12);
            }
            //根据付款类型获取相关的数据
            $saledata[$saledatakey]['typedata'] = $this->paytypes($saledataval['id'], $saledataval['paytype_id'], $res['status']);
            //处理一个付款登记对应多个备注
            $saledata[$saledatakey]['remark'] = getables('sale_payreg_remark', ['sale_payreg_id' => $saledataval['id']], 'id,remark');
        }
        //删除付款类型是支票不符合的数据(支票类型3，4)
        foreach ($saledata as $saledatakeys => $saledatavals) {
            if ($res['status'] != 7 && $saledatavals['paytype_id'] == 3 || $saledatavals['paytype_id'] == 4) {
                //表示点击的是除了支票收到中，没有存入账号的
                if (!$saledatavals['typedata']) {
                    unset($saledata[$saledatakeys]);
                }
            }
        }
        $saledata = array_values($saledata);//重置索引
        //计算总数
        foreach ($countdata as $countdatakey => $countdataval) {
            //根据付款类型获取相关的数据
            $countdata[$countdatakey]['typedata'] = $this->paytypes($countdataval['id'], $countdataval['paytype_id'], $res['status']);
        }
        foreach ($countdata as $countdatakeys => $countdatavals) {
            if ($res['status'] != 7 && $countdatavals['paytype_id'] == 3 || $countdatavals['paytype_id'] == 4) {
                if (!$countdatavals['typedata']) {
                    unset($countdata[$countdatakeys]);
                }
            }
        }
        $count = count($countdata);
        //处理每一个标签的数字
        $arrcount = $this->arrcount($maps, $res['status']);
        return array('data' => $saledata, 'count' => $count, 'arrcount' => $arrcount);
    }

    /*
     * 计算每一个标签的数据
     */
    protected function arrcount($maps, $status)
    {
        //这里的主要是方便搜索时，不会影响到其他的标签
        $ones = $twos = $threes = $fours = $fives = $sexs = $sevens = array();
        switch ($status) {
            case '1':
                $ones = $maps;
                break;
            case '2':
                $twos = $maps;
                break;
            case '3':
                $threes = $maps;
                break;
            case '4':
                $fours = $maps;
                break;
            case '5':
                $fives = $maps;
                break;
            case '6':
                $sexs = $maps;
            case '7':
                $sevens = $maps;
                break;
        }
        //待收款 确认收款 已完成 逾期 坏账
        $join = [
            ['sale_pay_index b', 'a.id=b.sale_payreg_id', 'LEFT'],//关联表
            ['sale c', 'c.id=b.sale_id', 'LEFT'],//销售表
        ];
        //新订单
        $joinone = [
            ['sale_pay_index b', 'a.id=b.sale_payreg_id', 'LEFT'],//关联表
            ['sale c', 'c.id=b.sale_id', 'LEFT'],//销售表
            ['sale_make d', 'c.id=d.sale_id', 'LEFT'],//配货表
        ];
        //新订单
        $reswhereone = $this->statuswhere(1)['salewhere'];
        $onedata = Db::name('sale_payreg')->alias('a')->join($joinone)->where(function ($query) use ($reswhereone) {
            $query->where($reswhereone);
        })->where(function ($query) use ($ones) {
            $query->whereOr($ones);
        })->field('a.id,a.paytype_id')->select();

        //去掉不符合要求的数据
        foreach ($onedata as $onedatakey => $onedataval) {
            //根据付款类型获取相关的数据
            $onedata[$onedatakey]['typedata'] = $this->paytypes($onedataval['id'], $onedataval['paytype_id'], 1);
        }
        //（在新订单中限制了付款类型）
        foreach ($onedata as $onedatakeys => $onedatavals) {
            if ($onedatavals['paytype_id'] == 3) {
                if (!$onedatavals['typedata']) {
                    unset($onedata[$onedatakeys]);
                }
            }
        }
        $one = count($onedata);
        //待收款
        $reswheretwo = $this->statuswhere(2)['salewhere'];

        $twodata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($reswheretwo) {
            $query->where($reswheretwo);
        })->where(function ($query) use ($twos) {
            $query->whereOr($twos);
        })->field('a.id,a.paytype_id')->select();

        //去掉不符合要求的数据
        foreach ($twodata as $twodatakey => $twodataval) {
            //根据付款类型获取相关的数据
            $twodata[$twodatakey]['typedata'] = $this->paytypes($twodataval['id'], $twodataval['paytype_id'], 2);
        }
        foreach ($twodata as $twodatakeys => $twodatavals) {
            if ($twodatavals['paytype_id'] == 3) {
                if (!$twodatavals['typedata']) {
                    unset($twodata[$twodatakeys]);
                }
            }
        }
        $two = count($twodata);
        //确认收款
        $reswherethree = $this->statuswhere(3)['salewhere'];
        $threedata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($reswherethree) {
            $query->where($reswherethree);
        })->where(function ($query) use ($threes) {
            $query->whereOr($threes);
        })->field('a.id,a.paytype_id')->select();
        //去掉不符合要求的数据
        foreach ($threedata as $threedatakey => $threedataval) {
            //根据付款类型获取相关的数据
            $threedata[$threedatakey]['typedata'] = $this->paytypes($threedataval['id'], $threedataval['paytype_id'], 3);
        }
        foreach ($threedata as $threedatakeys => $threedatavals) {
            if ($threedatavals['paytype_id'] == 3 || $threedatavals['paytype_id'] == 4) {
                if (!$threedatavals['typedata']) {
                    unset($threedata[$threedatakeys]);
                }
            }
        }
        $three = count($threedata);
        //已完成
        $reswherefour = $this->statuswhere(4)['salewhere'];
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $sevenday = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y')) - 1;
        $salewhereor['a.fail_at'] = ['between', "$sevenday,$endToday"];
        $salewhereor['a.check_id'] = session('userid');
        $fourdata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($reswherefour) {
            $query->where($reswherefour);
        })->where(function ($query) use ($fours) {
            $query->whereOr($fours);
        })->whereOr(function ($query) use ($salewhereor) {
            $query->where($salewhereor);
        })->field('a.id,a.paytype_id')->select();
        //去掉不符合要求的数据
        foreach ($fourdata as $fourdatakey => $fourdataval) {
            //根据付款类型获取相关的数据
            $fourdata[$fourdatakey]['typedata'] = $this->paytypes($fourdataval['id'], $fourdataval['paytype_id'], 4);
        }
        foreach ($fourdata as $fourdatakeys => $fourdatavals) {
            if ($fourdatavals['paytype_id'] == 3 || $fourdatavals['paytype_id'] == 4) {
                if (!$fourdatavals['typedata']) {
                    unset($fourdata[$fourdatakeys]);
                }
            }
        }
        $four = count($fourdata);
        //逾期
        $reswherefive = $this->statuswhere(5)['salewhere'];
        $fivedata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($reswherefive) {
            $query->where($reswherefive);
        })->where(function ($query) use ($fives) {
            $query->whereOr($fives);
        })->field('a.id,a.paytype_id')->select();
        //去掉不符合要求的数据
        foreach ($fivedata as $fivedatakey => $fivedataval) {
            //根据付款类型获取相关的数据
            $fivedata[$fivedatakey]['typedata'] = $this->paytypes($fivedataval['id'], $fivedataval['paytype_id'], 5);
        }
        foreach ($fivedata as $fivedatakeys => $fivedatavals) {
            if ($fivedatavals['paytype_id'] == 3 || $fivedatavals['paytype_id'] == 4) {
                if (!$fivedatavals['typedata']) {
                    unset($fivedata[$fivedatakeys]);
                }
            }
        }
        $five = count($fivedata);

        //坏账
        $reswheresex = $this->statuswhere(6)['salewhere'];
        $sexdata = Db::name('sale_payreg')->alias('a')->join($join)->where(function ($query) use ($reswheresex) {
            $query->where($reswheresex);
        })->where(function ($query) use ($sexs) {
            $query->whereOr($sexs);
        })->field('a.id,a.paytype_id')->select();
        //去掉不符合要求的数据
        foreach ($sexdata as $sexdatakey => $sexdataval) {
            //根据付款类型获取相关的数据
            $sexdata[$sexdatakey]['typedata'] = $this->paytypes($sexdataval['id'], $sexdataval['paytype_id'], 6);
        }
        foreach ($sexdata as $sexdatakeys => $sexdatavals) {
            if ($sexdatavals['paytype_id'] == 3 || $sexdatavals['paytype_id'] == 4) {
                if (!$sexdatavals['typedata']) {
                    unset($sexdata[$sexdatakeys]);
                }
            }
        }
        $sex = count($sexdata);
        //支票收到
        $reswhereseven = $this->statuswhere(7)['salewhere'];
        $joinseven = [
            ['sale_pay_index b', 'a.id=b.sale_payreg_id', 'LEFT'],//关联表
            ['sale c', 'c.id=b.sale_id', 'LEFT'],//销售表
            ['sale_pay_cheque d', 'a.id=d.sale_payreg_id', 'LEFT'],//支票表
        ];
        $seven = Db::name('sale_payreg')->alias('a')->join($joinseven)->where(function ($query) use ($reswhereseven) {
            $query->where($reswhereseven);
        })->where(function ($query) use ($sevens) {
            $query->whereOr($sevens);
        })->count();
        return array(
            'one' => $one == 0 ? '' : $one,
            'two' => $two == 0 ? '' : $two,
            'three' => $three == 0 ? '' : $three,
            'four' => $four == 0 ? '' : $four,
            'five' => $five == 0 ? '' : $five,
            'sex' => $sex == 0 ? '' : $sex,
            'seven' => $seven == 0 ? '' : $seven
        );
    }

    /*
   * $pregid 付款登记id
   * $typeid 付款登记类型id  1 现金 2代金券 3支票 4期票 5 转账 6银行单 7期账
   * $lang  语言
   */
    protected function paytypes($pregid, $typeid, $status)
    {
        $sale_paydata = array();
        if ($typeid == 3 || $typeid == 4) {
            //支票登记
            $mapcheque['sale_payreg_id'] = $pregid;
            //除了支票收到
            if ($status != 7) {
                //必须含有支付账号
                $mapcheque['checkin_day'] = array('gt', 0);//表示已存入账号了
                $mapcheque['used_day'] = 0;//没有使用日期
            }
            //这里的付款登记只会对应一个付款方式
            $sale_paydata = Db::name('sale_pay_cheque')->field('sale_id,bank_id,number,signature,amount,scan_url,accounts_id,pay_day')->where($mapcheque)->find();
            if ($sale_paydata) {
                if ($sale_paydata['bank_id'] > 0) {
                    $sale_paydata['bank_name'] = $this->strchange($sale_paydata['bank_id'], 3)['name'];;//开票银行
                } else {
                    $sale_paydata['bank_name'] = '';
                }
                //付款日期
                $sale_paydata['pay_day_date'] = getTimeDate($sale_paydata['pay_day'], 15);
                //收款账号
                $account_info = getinfo($sale_paydata['accounts_id'], 'accounts');
                $accontbankname = $this->strchange($account_info['banks_id'], 3)['name'];//开票银行
                $sale_paydata['accountnumber'] = $accontbankname . '/' . $this->strchange($account_info['account_num'], 1);//存入账号
                $sale_paydata['accountname'] = $account_info['bankname'];
            }
        } elseif ($typeid == 5) {
            //转账登记
            $maptransfer['sale_payreg_id'] = $pregid;
            $maptransfer['sale_payreg_id'] = $pregid;
            $sale_paydata = Db::name('sale_pay_transfer')->field('sale_id,co_bank_id,pay_day,number,amount,scan_url,account_id')->where($maptransfer)->find();
            if ($sale_paydata) {
                //汇出账号的信息
                $co_banknumber = $co_bankname = '';
                $co_bankinfo = getinfo($sale_paydata['co_bank_id'], 'co_bank');
                //汇出账号
                if ($co_bankinfo) {
                    $bankname = $this->strchange($co_bankinfo['banks_id'], 3)['name'];
                    $co_banknumber = $bankname . '/' . $this->strchange($co_bankinfo['account_num'], 1);
                    $co_bankname = $co_bankinfo['bankname'];
                }
                $sale_paydata['co_banknumber'] = $co_banknumber;
                //汇出开户行
                $sale_paydata['co_bankname'] = $co_bankname;

                //流水号
                $sale_paydata['number'] = $this->strchange($sale_paydata['number'], 2);

                //存入账号
                $account_banknumber = $account_bankname = '';
                $account_bankinfo = getinfo($sale_paydata['account_id'], 'accounts');
                if ($account_bankinfo) {
                    $accontbankname = $this->strchange($account_bankinfo['banks_id'], 3)['name'];
                    $account_banknumber = $accontbankname . '/' . $this->strchange($account_bankinfo['account_num'], 1);//汇入账号
                    $account_bankname = $account_bankinfo['bankname'];
                }
                $sale_paydata['account_banknumber'] = $account_banknumber;
                //汇入开户行
                $sale_paydata['account_bankname'] = $account_bankname;
            }
        } elseif ($typeid == 6) {
            //银行单
            $mapbill['sale_payreg_id'] = $pregid;
            $sale_paydata = Db::name('sale_pay_bill')->field('sale_id,pay_day,number,amount,account_id,create_id')->where($mapbill)->find();
            if ($sale_paydata) {
                $bill_banknumber = $bill_bankname = '';
                $account_bill = getinfo($sale_paydata['account_id'], 'accounts');
                if ($account_bill) {
                    $bankbillname = $this->strchange($account_bill['banks_id'], 3)['name'];
                    $bill_banknumber = $bankbillname . '/' . $this->strchange($account_bill['account_num'], 1);
                    $bill_bankname = $account_bill['bankname'];
                }
                $sale_paydata['bill_banknumber'] = $bill_banknumber;
                //开户行
                $sale_paydata['bill_bankname'] = $bill_bankname;
                //流水号
                $sale_paydata['number'] = $this->strchange($sale_paydata['number'], 2);

                //开单时间
                $sale_paydata['pay_day_date'] = getTimeDate($sale_paydata['pay_day'], 15);
                //开单人
                $sale_paydata['create_name'] = getinfo($sale_paydata['create_id'], 'admin')['nickname'];
            }
        }
        return $sale_paydata;
    }

    /*
     * 已收到 未收到 查看 数据接口显示
     */

    public function getsalepaycode($res)
    {
        $join = [
            ['sale_pay_index b', 'a.id=b.sale_payreg_id', 'LEFT'],//关联表
            ['sale c', 'c.id=b.sale_id', 'LEFT'],//销售表
        ];
        $salewhere['c.id'] = $res['sale_id'];//销售id

        //获取的是销售订单下付款登记数据
        $saledata = Db::name('sale_payreg')->alias('a')->join($join)->where($salewhere)->field('a.*,b.sale_id,c.priority,c.pay,c.pledge,c.saler_id,c.co_id,c.delivery_type_id,c.co_branch_id')->select();
        //必须之前的 并且没有确认支付的`
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'))-1;
        foreach ($saledata as $saledatakey => $saledataval) {
            //收款日期
            $saledata[$saledatakey]['pay_date'] = getTimeDate($saledataval['pay_day'], 15);
            //付款方式
            $pay_typewhere['mkey'] = 'sale_pay_type_' . $saledataval['paytype_id'];
            $saledata[$saledatakey]['paytype_name'] = getlangname('multi_lang', $pay_typewhere, $res['lang']);
            $saledata[$saledatakey]['managename'] = getinfo($saledataval['update_id'], 'admin')['nickname'];
            $saledata[$saledatakey]['update_date'] = getTimeDate($saledataval['update_at'], 12);
            // 没有确认支付的,并且没有逾期`
            if ($saledataval['pay_day'] >= $beginToday && $saledataval['check_id'] == 0) {
                //没有逾期可以显示
                $saledata[$saledatakey]['checks'] = 1;
            } else {
                $saledata[$saledatakey]['checks'] = 2;
            }
            //判断是否有确认者
            if ($saledataval['check_id'] != 0) {
                //含有支付者
                $saledata[$saledatakey]['check_name'] = getinfo($saledataval['check_id'], 'admin')['nickname'];
                if ($saledataval['success_at'] > 0) {
                    //支付成功
                    $saledata[$saledatakey]['success_fail_date'] = getTimeDate($saledataval['success_at'], 15);
                    //设置颜色的显示
                    $saledata[$saledatakey]['class'] = 'green';
                } else {
                    //支付失败
                    $saledata[$saledatakey]['success_fail_date'] = getTimeDate($saledataval['fail_at'], 15);
                    $saledata[$saledatakey]['class'] = 'red';
                }
            } else {
                $saledata[$saledatakey]['check_name'] = '';
                $saledata[$saledatakey]['success_fail_date'] = '';
                $saledata[$saledatakey]['class'] = '';
            }
            //根据付款类型获取相关的数据
            $saledata[$saledatakey]['typedata'] = $this->paytypes($saledataval['id'], $saledataval['paytype_id'], 1);
            //处理一个付款登记对应多个备注
            $saledata[$saledatakey]['remark'] = getables('sale_payreg_remark', ['sale_payreg_id' => $saledataval['id']], 'id,remark');
        }
        //去除不符合要求付款登记(支票收到这里是不会有已收到，未收到，查看的按钮)
        foreach ($saledata as $saledatakeys => $saledatavals) {
            if ($saledatavals['paytype_id'] == 3 || $saledatavals['paytype_id'] == 4) {
                if (!$saledatavals['typedata']) {
                    unset($saledata[$saledatakeys]);
                }
            }
        }
        $saledata = array_values($saledata);
        $huaipay = 0;//坏账合计
        foreach ($saledata as $saledatakeyss => $saledatavalss) {
            //坏账合计
            if ($saledatavalss['fail_at'] > 0 && $saledatavalss['paid'] == 0) {
                $huaipay += $saledatavalss['amount'];
            }
        }

        //获取这个销售订单的数据
        $saleresinfo = getinfo($res['sale_id'], 'sale');
        $invoiceinfo = getinfo($res['sale_id'], 'sale_invoice');

        //送货方式
        $delivery_typewhere['mkey'] = 'sale_delivery_type_' . $saleresinfo['delivery_type_id'];
        $delivergoods = getlangname('multi_lang', $delivery_typewhere, $res['lang']);

        $alreadypay = $saleresinfo['paid'];//已收金额
        $amountpay = $this->countsale($saleresinfo['id'], $saledata);//销售订单下登记金额合计
        //发票号 开票员 开票时间
        $drawername = $drawertime = '';
        if ($invoiceinfo) {
            $drawername = getinfo($invoiceinfo['drawer_id'], 'admin')['nickname'];
            $drawertime = getTimeDate($invoiceinfo['drawer_at'], 12);
        }
        //判断点击的付款登记是否已经付款
        $payreginfo=getinfo($res['payregid'],'sale_payreg','check_id,pay_day,amount');
        //表示这个付款登记没有付款
        $payregarr=array();
        if ($payreginfo['pay_day'] >= $beginToday && $payreginfo['check_id'] == 0) {
            $payregarr=array(
                'payregid'=>$res['payregid'],
                'amount'=>$payreginfo['amount']
            );
        }
        $array = array(
            'sale_id' => $saleresinfo['id'],
            'company_name' => getinfo($saleresinfo['co_id'], 'company')['name'],
            'company_id'=>$saleresinfo['co_id'],
            'pledge' => $saleresinfo['pledge'] == 1 ? 'YES' : 'NO',
            'fapiaonum' => $this->strchange($invoiceinfo['number'], 2),//发票号
            'drawername' => $drawername,//开票员
            'drawertime' => $drawertime,//开票时间
            'pay' => $saleresinfo['pay'],//应付款
            'dengjipay' => $amountpay,//登记金额
            'alreadypay' => $alreadypay,//到账金额
            'nopay' => $saleresinfo['pay'] - $alreadypay,//应收金额-已收金额=未确认金额
            'saler_name' => getinfo($saleresinfo['saler_id'], 'admin')['nickname'],//业务员
            'drawuser_create' => getinfo($saleresinfo['create_id'], 'admin')['nickname'],//开单人
            'drawdate_time_create' => getTimeDate($saleresinfo['create_at'], 12),//开单时间
            'drawuser_update' => getinfo($saleresinfo['update_id'], 'admin')['nickname'],//更新人
            'drawdate_time_update' => getTimeDate($saleresinfo['update_at'], 12),//更新时间
            'delivergoods' => $delivergoods,//送货方式
            'code' => $res['code'],//设置显示具体的modelfooter
            'huaipay' => $huaipay,//坏账金额
        );
        //获取这个订单的相关的付款信息
        return array('data' => $saledata, 'saledata' => $array,'batch'=>$payregarr);
    }

    /*
     * 取消到账按钮 确认到账 按钮点击
     */
    public function onyesaccount($res)
    {
        if ($res['noaccount'] == 1) {
            //未收到按钮点击确认
            if (!isset($res['batch']) || !$res['batch']) {
                return array('msg' => '请选择要取消的付款登记', 'status' => 2);
            }
        } else {
            //已收到按钮点击确认
            if (!isset($res['batch']) || !$res['batch']) {
                return array('msg' => '请选择要付款的付款登记', 'status' => 2);
            }
        }
        if($res['batch']){
           if(!is_numeric($res['batch'][0])){
               return array('msg' => '逾期款项无法确认', 'status' => 2);
           }
        }
        //将这个付款登记的金额，进行增加
        $mapayreg['a.id'] = ['in', $res['batch']];
        $amountdatas = Db::name('sale_payreg')->alias('a')->join('nt_sale_pay_index b', 'a.id=b.sale_payreg_id', 'left')->where($mapayreg)->field('a.id,a.amount,a.paytype_id,b.sale_id')->select();

        $mapsale['a.id'] = array_unique(array_column($amountdatas, 'sale_id'))[0];//获取到这个付款登记对应的销售id
        //销售订单的付款登记ids
        $payregids = array_column(Db::name('sale')->where($mapsale)->alias('a')->join('nt_sale_pay_index b', 'a.id=b.sale_id', 'left')->field('b.sale_payreg_id')->select(), 'sale_payreg_id');

        $update['check_id'] = $update['update_id'] = session('userid');
        $update['update_at'] = time();
        if ($res['noaccount'] == 1) {
            //未收到按钮点击
            $update['fail_at'] = time();
            $mapsalefail['co_id']=$res['co_id'];
            foreach ($amountdatas as $amountdataskey => $amountdatasval) {
                $mapsalefail['pay_type_id']=$amountdatasval['paytype_id'];
                $infofail=Db::name('co_sale_fail')->where($mapsalefail)->find();
                if(!$infofail){
                    //添加失败次数
                    $failesale['co_id']=$res['co_id'];
                    $failesale['pay_type_id']=$amountdatasval['paytype_id'];
                    $failesale['fail']=1;
                    $failesale['update_at']=$failesale['create_at']=time();
                    Db::name('co_sale_fail')->insert($failesale);
                }else{
                    //更新失败次数
                    Db::name('co_sale_fail')->where($mapsalefail)->setInc('fail');
                    Db::name('co_sale_fail')->where($mapsalefail)->update(['update_at'=>time()]);
                }
                //统计公司支付失败的次数，在一个支付类型下
                Db::name('sale_payreg')->where('id', $amountdatasval['id'])->update($update);
                //更新其他的数据 （对应的付款方式表和销售表）
                $this->updatedata($amountdatasval, $res['noaccount']);
            }
        } else {
            //已收到按钮点击
            $update['success_at'] = time();
            foreach ($amountdatas as $amountdataskey => $amountdatasval) {
                $update['paid'] = $amountdatasval['amount'];
                //更新付款登记表
                Db::name('sale_payreg')->where('id', $amountdatasval['id'])->update($update);
                // 销售订单表
                Db::name('sale')->where('id', $amountdatasval['sale_id'])->setInc('paid', $amountdatasval['amount']);
                //更新其他的数据
                $this->updatedata($amountdatasval, $res['noaccount']);
            }
        }
        return array('msg' => '确认成功', 'status' => 1);
    }

    /*
     * 付款登记其他数据的更新
     */
    protected function updatedata($data, $code)
    {
        $update['check_id'] = $update['update_id'] = session('userid');
        $update['update_at'] = time();
        if ($code == 1) {
            //点击确认及金额没有到账
            $update['fail_at'] = time();
            //更新确认者和失败时间
            if ($data['paytype_id'] == 3 || $data['paytype_id'] == 4) {
                //3,4是支票登记
                Db::name('sale_pay_cheque')->where('sale_payreg_id', $data['id'])->update($update);
            } elseif ($data['paytype_id'] == 5) {
                //转账登记
                Db::name('sale_pay_transfer')->where('sale_payreg_id', $data['id'])->update($update);
            } elseif ($data['paytype_id'] == 6) {
                //银行单
                Db::name('sale_pay_bill')->where('sale_payreg_id', $data['id'])->update($update);
            }
        } else {
            $update['success_at'] = time();
            //点击的是金额已经到账
            if ($data['paytype_id'] == 3 || $data['paytype_id'] == 4) {
                //3是支票登记
                Db::name('sale_pay_cheque')->where('sale_payreg_id', $data['id'])->update($update);
            } elseif ($data['paytype_id'] == 5) {
                //转账登记
                Db::name('sale_pay_transfer')->where('sale_payreg_id', $data['id'])->update($update);
            } elseif ($data['paytype_id'] == 6) {
                //银行单
                Db::name('sale_pay_bill')->where('sale_payreg_id', $data['id'])->update($update);
            }
        }
    }


    /*
     * 恢复按钮的点击(只有恢复失败的订单 坏账)
     */
    public function huisale($res,$payreginfo)
    {
        $map['co_id']=$payreginfo['co_id'];
        $map['pay_type_id']=$payreginfo['paytype_id'];
        Db::name('co_sale_fail')->where($map)->setDec('fail');//减少失败次数
        Db::name('co_sale_fail')->where($map)->update(['update_at'=>time()]);
        $update['update_id'] = session('userid');
        $update['update_at'] = time();
        $update['fail_at'] = 0;
        $update['check_id'] = 0;
        $one = Db::name('sale_payreg')->where('id', $res['id'])->update($update);
        $this->updatequxiao($payreginfo, 2);
        if ($one) {
            return array('status' => 1, 'msg' => '恢复成功');
        } else {
            return array('msg' => '恢复失败', 'status' => 0);
        }

    }

    /*
     * (已完成)取消收账 (支票收到)取消
     */
    public function quxiaosale($res, $code)
    {
        if ($code == 1) {
            $update['check_id'] = 0;
            $update['update_id'] = session('userid');
            $update['update_at'] = time();
            //判断这个订单是成功的订单还是失败的付款登记
            $salepayreginfo = getinfo($res['id'], 'sale_payreg');
            if ($salepayreginfo['success_at'] > 0) {
                $update['paid'] = $update['success_at'] = 0;
                //表示成功的付款登记
                Db::name('sale_payreg')->where('id', $res['id'])->update($update);//更新付款登记表
                //销售订单表的数据进行减去
                Db::name('sale')->where('id', $res['sale_id'])->setDec('paid', $salepayreginfo['amount']);
                $this->updatequxiao($salepayreginfo, 1);
            } else {
                $map['co_id']=$salepayreginfo['co_id'];
                $map['pay_type_id']=$salepayreginfo['paytype_id'];
                Db::name('co_sale_fail')->where($map)->setDec('fail');//减少失败次数
                Db::name('co_sale_fail')->where($map)->update(['update_at'=>time()]);
                $update['fail_at'] = 0;
                //表示的是付款失败的登记
                Db::name('sale_payreg')->where('id', $res['id'])->update($update);
                $this->updatequxiao($salepayreginfo, 2);
            }
            return array('msg' => '取消成功', 'status' => 1);
        } elseif ($code == 2) {
            $gotdata['got_id'] = $gotdata['got_at'] = 0;
            $gotdata['update_id'] = session('userid');
            $gotdata['update_at'] = time();
            //更新数据
            $resid = Db::name('sale_pay_cheque')->where('id', $res['id'])->update($gotdata);
            return array('msg' => '取消成功', 'status' => 1);
        }
    }

    /*
     * 已完成(取消收账)更新其他表
     */
    protected function updatequxiao($salepayreginfo, $code)
    {
        $update['update_id'] = session('userid');
        $update['update_at'] = time();
        $update['check_id'] = 0;
        if ($code == 1) {
            //付款成功的取消收账
            $update['success_at'] = 0;
            if ($salepayreginfo['paytype_id'] == 3 || $salepayreginfo['paytype_id'] == 4) {
                //3,4是支票登记
                Db::name('sale_pay_cheque')->where('sale_payreg_id', $salepayreginfo['id'])->update($update);
            } elseif ($salepayreginfo['paytype_id'] == 5) {
                //转账登记
                Db::name('sale_pay_transfer')->where('sale_payreg_id', $salepayreginfo['id'])->update($update);
            } elseif ($salepayreginfo['paytype_id'] == 6) {
                //银行单
                Db::name('sale_pay_bill')->where('sale_payreg_id', $salepayreginfo['id'])->update($update);
            }
        } else {
            $update['fail_at'] = 0;
            //付款失败的取消收账
            if ($salepayreginfo['paytype_id'] == 3 || $salepayreginfo['paytype_id'] == 4) {
                //3是支票登记
                Db::name('sale_pay_cheque')->where('sale_payreg_id', $salepayreginfo['id'])->update($update);
            } elseif ($salepayreginfo['paytype_id'] == 5) {
                //转账登记
                Db::name('sale_pay_transfer')->where('sale_payreg_id', $salepayreginfo['id'])->update($update);
            } elseif ($salepayreginfo['paytype_id'] == 6) {
                //银行单
                Db::name('sale_pay_bill')->where('sale_payreg_id', $salepayreginfo['id'])->update($update);
            }
        }
    }

    /*
     * 收到点击 （支票收到）
     */
    public function receivesale($res)
    {
        $gotdata['update_id'] = $gotdata['got_id'] = session('userid');
        $gotdata['update_at'] = $gotdata['got_at'] = time();
        //更新数据
        $resid = Db::name('sale_pay_cheque')->where('id', $res['id'])->update($gotdata);
        if ($resid !== false) {
            return array('msg' => '确认已收到', 'status' => 1);
        } else {
            return array('msg' => '确认失败', 'status' => 0);
        }

    }

    /*
     * 计算同一个订单下的合计
     */
    protected function countsale($saleid, $saledata)
    {
        $count = 0;
        //相同订单下合计金额
        foreach ($saledata as $saledatakey => $saledataval) {
            if ($saledataval['sale_id'] == $saleid && $saledataval['fail_at']==0) {
                $count += $saledataval['amount'];
            }
        }
        return $count;
    }


    /*
     * 条件筛选
     * a 销售表
     * b 销售订单与付款登记关联表
     * c 付款登记表
     * d 付款登记备注表
     */
    protected function statuswhere($status)
    {
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'))-1;
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        //7天之前的时间
        $sevenday = mktime(0, 0, 0, date('m'), date('d') - 7, date('Y')) - 1;
        //1个月的的坏账
        $thirtyday = mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')) - 1;
        $mapsale = array();
        switch ($status) {
            //新订单
            case '1':
                //付款登记表
                $mapsale['a.paytype_id'] = array('in', '1,3,5');//现金 支票 转账(类型)
                $mapsale['a.check_id'] = 0;//没有支付人
                $mapsale['a.pay_day'] = ['between', "$beginToday,$endToday"];//付款登记必须是今天的
                //销售定单表
                $mapsale['c.pledge'] = 1;//含有定金
                $mapsale['c.create_at'] = ['between', "$beginToday,$endToday"];//销售订单必须是当天
                $mapsale['d.sale_id'] = null;//销售订单还没有配货
                break;
            //待收款
            case '2':
                $mapsale['a.paytype_id'] = array('in', '1,3,5');//现金 支票 转账（类型）
                $mapsale['a.check_id'] = 0;//没有支付人
                $mapsale['a.pay_day'] = ['between', "$beginToday,$endToday"];//付款登记必须是今天的
                //销售定单表
                $mapsale['c.pledge'] = 0;//没有定金
                $mapsale['c.create_at'] = ['between', "$beginToday,$endToday"];//销售订单必须是当天
                break;
            //确认收款
            case '3':
                $mapsale['a.paytype_id'] = array('in', '1,3,4,5,6,7');//现金 支票 期票 转账 银行单 期账
                $mapsale['a.check_id'] = 0;//没有支付人
                $mapsale['a.pay_day'] = array('gt', $endToday);//不是今天的单子
                //销售定单表
              //  $mapsale['c.create_at'] = array('lt', $beginToday); //不是今天的
                break;
            //已经完成的订单
            case '4':
                //查看7天内成功的订单（只能看本人确认的）7天以内的收款记录（包括成功的，或者失败的）
                $mapsale['a.check_id'] = session('userid');
                $mapsale['a.success_at'] = ['between', "$sevenday,$endToday"];//完成的金额中amount 等于paid
                break;
            //逾期
            case '5':
                //付款时间大于现在的时间 还没有确认者
                $mapsale['a.pay_day'] = array('lt', $beginToday);
                $mapsale['a.check_id'] = 0;
                break;
            //坏账
            case '6':
                //30天以后的坏账 付款收不到的
                $mapsale['a.pay_day'] = ['between', "$thirtyday,$endToday"];//查看的30天内的坏账
                $mapsale['a.fail_at'] = array('gt', 0);//失败时间大于0
                break;
            //支票收到
            case '7':
                $mapsale['a.paytype_id'] = array('in', '3,4');//支票
                $mapsale['d.used_day'] = 0;//没有使用
                $mapsale['d.checkin_day'] = 0;//没有存入
                break;
        }
        return array(
            'salewhere' => $mapsale,
        );
    }

    /*
     * 对获取到的银行账号进行加密
     */
    protected function strchange($str, $code)
    {
        if ($code == 1) {
            return substr($str, 0, 3) . '***' . substr($str, 7);
        } elseif ($code == 2) {
            $arr = str_split($str, 4);//4的意思就是专每4个为一组
            return implode(' ', $arr);
        } elseif ($code == 3) {
            //对银行处理
            return getinfo($str, 'banks');
        }
    }
}